<?php

namespace Models;

class PurchaseRecord extends Model
{
	protected $_table = 'purchase_records';

	protected $_default_filter = 'purchase_records.is_delete=0';

	protected $_belongs = [
		'product' => [
			'class' => Product::class,
			'foreign' => 'id',
			'belongs_key' => 'product_id',
		],
		'item' => [
			'class' => Item::class,
			'foreign' => 'id',
			'belongs_key' => 'item_id',
		]
	];

	public function stock($item_id,$stock){
		if($stock == 0) return false;

		if($stock>0){
			$purchase_records = $this->where('item_id',$item_id)->where('stock < number')->order_by('expire','desc')->get();
			if(!$purchase_records) return false;
			$st = $stock;
			foreach ($purchase_records as $record) {
				$dn = $record['number'] - $record['stock'];
				if($dn >= $st){
					$ns = $record['stock'] + $st;
					$this->update($record['id'],['stock'=>$ns]);
					break;
				}else{
					$st = $st - $dn;
					$this->update($record['id'],['stock'=>$record['number']]);
				}
			}

		}else if($stock<0){
			$purchase_records = $this->where('item_id',$item_id)->where('stock >',0)->order_by('expire','asc')->get();
			if(!$purchase_records) return false;
			$st = abs($stock);
			foreach ($purchase_records as $record) {
				if($record['stock'] >= $st){
					$ns = $record['stock'] - $st;
					$this->update($record['id'],['stock'=>$ns]);
					break;
				}else{
					$st = $st - $record['stock'];
					$this->update($record['id'],['stock'=>0]);
				}
			}
		}

		return true;

	}
}